package com.qf.controller;

import com.alibaba.fastjson.JSONObject;
import com.qf.captcha.CaptchaCodeManager;
import com.qf.pojo.DtsAdmin;
import com.qf.service.*;
import com.qf.util.*;
import com.qf.util.Base64;
import com.qf.util.UUID;


import lombok.extern.log4j.Log4j;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @author 邢式瑞
 * @version 1.0
 * @project E-commercebackGroundManagementSystem
 * @date 2022/9/20 14:56
 */
@RestController
@RequestMapping("/admin")
@Slf4j
@CrossOrigin
public class AdminAuthController {
    @Autowired
    private DtsRoleService roleService;

    @Autowired
    private PermissionService permissionService;
    @Autowired
    private DtsUserService dtsUserService;
    @Autowired
    private GoodsService goodsService;
    @Autowired
    private ProductService productService;
    @Autowired
    private OrderService orderService;
    @Autowired
    private ApplicationContext context;


    @GetMapping("/auth/captchaImage")
    public Object  captchaImage() throws IOException {
        String code = VerifyCodeUtils.generateVerifyCode(4);
        String uuid = UUID.randomUUID().toString();
        //缓存验证码数字
        Boolean isSuccess= CaptchaCodeManager.addToCache(uuid,code,null);
      if(!isSuccess){
          log.error("【验证码保存失败】 验证码是:"+code);
      }
      //输出流
        ByteArrayOutputStream os = new ByteArrayOutputStream();
      VerifyCodeUtils.outputImage(116,40,os,code);
       //江流转化成二进制
    String  encode =  Base64.encode(os.toByteArray());

        Map data = new HashMap();
        data.put("img",encode);
        data.put("uuid",uuid);
        return ResponseUtil.ok(data);
    }



    @PostMapping("/auth/login")
    public  Object login(@RequestBody String body ){
        String username = JacksonUtil.parseString(body,"username");
        String password = JacksonUtil.parseString(body, "password");
        String code = JacksonUtil.parseString(body, "code");
        String uuid = JacksonUtil.parseString(body, "uuid");
        System.out.println(code);
//        if(StringUtils.isEmpty(code)){
//            return AdminResponseUtil.fail(807,"验证码不能为空");
//        }
        if(StringUtils.isEmpty(username)){
            return AdminResponseUtil.fail(808,"用户名不能为空");
        }
        if (StringUtils.isEmpty(password)) {
            return AdminResponseUtil.fail(809,"密码不能为空");
        }
        String cachedCaptcha = CaptchaCodeManager.getCachedCaptcha(uuid);
        System.out.println(cachedCaptcha);
//        if(!cachedCaptcha.equalsIgnoreCase(code)){
//            return AdminResponseUtil.fail(AdminResponseCode.AUTH_CAPTCHA_ERROR);
//        }
        UsernamePasswordToken usernamePasswordToken =  new UsernamePasswordToken(username,password);
        Subject subject = SecurityUtils.getSubject();
        try {
            subject.login(usernamePasswordToken);
        }catch (UnknownAccountException e){
            return AdminResponseUtil.fail(AdminResponseCode.ADMIN_INVALID_ACCOUNT_ERR);
        }catch (IncorrectCredentialsException e){
            return AdminResponseUtil.fail(AdminResponseCode.ADMIN_INVALID_PASSWORD_ERR);
        }catch (LockedAccountException e){
            return AdminResponseUtil.fail(AdminResponseCode.ADMIN_LOCK_ACCOUNT);
        }
        return ResponseUtil.ok(subject.getSession().getId());
    }
/**
 * {
 *     "errno":0,
 *     "data":{
 *         "roles":["超级管理员"],
 *         "name":"qianfeng",
 *         "perms":["*"],
 *         "avatar":"https://dss1.bdstatic.com/6OF1,499686101&fm=85&app=79&f=JPEG?w=121&h=75&s=81B24C32D40"
 *     },
 *     "errmsg":"成功"
 * }
 */
    @GetMapping("/auth/info")
    public Object info(){
        Subject subject = SecurityUtils.getSubject();
        DtsAdmin admin= (DtsAdmin)subject.getPrincipal();
        Map<String, Object> data = new HashMap<>();
        data.put("name", admin.getUsername());
        data.put("avatar", admin.getAvatar());
        Integer[] roleIds = admin.getRoleIds();
        Set<String> roles = roleService.queryByIds(roleIds);
        Set<String> permissions = permissionService.queryByRoleIds(roleIds);
        data.put("roles", roles);


       // data.put("perms", Arrays.asList("admin:storage:delete"));
        data.put("perms", toApi(permissions));

        log.info("【请求结束】系统管理->用户信息获取,响应结果:"+JSONObject.toJSONString(data));
        return ResponseUtil.ok(data);
    }


    @PostMapping("/auth/logout")
    public  Object logout(){

        Subject subject = SecurityUtils.getSubject();
        subject.logout();
        return ResponseUtil.ok();
    }
//@PostMapping("/profile/password")
//    public  Object resetPassword(@RequestBody String body){
//
//
//}
private Collection<String> toApi(Set<String> permissionList) {

    List<Permission> permissions = PermissionUtil.listPermission(context, "com.qf");
    System.out.println(permissions.toString());
    if(permissionList.contains("*")){
        return Arrays.asList("*");
    }
    System.out.println(permissions.get(1).getRequiresPermissions().value()[0]);
    return permissions.stream().filter(permission -> {
        if(permissionList.contains(permission.getRequiresPermissions().value()[0])){
            return true;
        }else {
            return false;
        }
    }).map(permission -> {
                return permission.getApi();
            })
            .collect(Collectors.toSet());
}
//RL: http://localhost:8080/admin/profile/password


}
